package com.example.show_auto.data

import android.content.Context
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import okhttp3.OkHttpClient
import okhttp3.Request
import java.io.IOException
import java.io.File

/**
 * 游戏数据管理器
 * 负责加载和管理游戏数据
 */
class GameDataManager(private val context: Context) {
    
    private val gson = Gson()
    private val httpClient = OkHttpClient()
    
    // 数据URL（使用我们之前抓取的数据）
    private val dataUrl = "https://h5.baochaojianghu.com/data/data.min.json"
    
    // 缓存的游戏数据
    private var cachedGameData: GameData? = null

    /**
     * 清除缓存，强制重新加载数据
     */
    fun clearCache() {
        cachedGameData = null
    }
    
    /**
     * 加载游戏数据
     */
    suspend fun loadGameData(): Result<GameData> = withContext(Dispatchers.IO) {
        try {
            // 如果已有缓存，直接返回
            cachedGameData?.let { return@withContext Result.success(it) }
            
            // 加载游戏数据（优先同步数据，其次assets原始数据）
            val gameData = loadFromAssets()
            if (gameData != null) {
                cachedGameData = gameData
                return@withContext Result.success(gameData)
            }
            
            // 如果都失败了，返回模拟数据
            val mockData = createMockData()
            cachedGameData = mockData
            Result.success(mockData)
            
        } catch (e: Exception) {
            Result.failure(e)
        }
    }
    
    /**
     * 加载游戏数据（统一数据源）
     * 优先使用同步后的数据，如果没有则使用assets原始数据
     */
    private fun loadFromAssets(): GameData? {
        return try {
            // 首先尝试从内部存储读取同步后的数据
            val syncedFile = File(context.filesDir, "game_data.json")
            
            // 优先从网络同步的缓存文件读取
            if (syncedFile.exists() && syncedFile.length() > 0) {
                try {
                    val jsonString = syncedFile.readText()
                    val gameData = parseGameData(jsonString)
                    return gameData
                } catch (e: Exception) {
                    // 缓存文件损坏，删除并从assets重新加载
                    syncedFile.delete()
                }
            }
            
            // 从assets读取
            val inputStream = context.assets.open("game_data.json")
            val jsonString = inputStream.bufferedReader().use { it.readText() }
            return parseGameData(jsonString)
        } catch (e: Exception) {
            null
        }
    }
    
    /**
     * 从网络加载数据
     */
    private fun loadFromNetwork(): GameData? {
        return try {
            val request = Request.Builder()
                .url(dataUrl)
                .build()
            
            val response = httpClient.newCall(request).execute()
            if (response.isSuccessful) {
                val jsonString = response.body?.string()
                jsonString?.let { parseGameData(it) }
            } else {
                null
            }
        } catch (e: IOException) {
            null
        }
    }
    
    /**
     * 从网络同步游戏数据
     * @return 同步结果
     */
    suspend fun syncGameDataFromNetwork(): Result<String> = withContext(Dispatchers.IO) {
        try {
            // 使用当前时间戳作为参数，避免科学计数法
            val timestamp = System.currentTimeMillis().toString()
            val url = "https://h5.baochaojianghu.com/data/data.min.json?v=$timestamp"
            val request = Request.Builder()
                .url(url)
                .build()
            
            val response = httpClient.newCall(request).execute()
            if (response.isSuccessful) {
                val jsonString = response.body?.string()
                if (jsonString != null) {
                    // 验证数据格式是否正确
                    val gameData = parseGameData(jsonString)
                    if (gameData != null) {
                        // 保存到内部存储，覆盖旧数据
                        saveGameDataToFile(jsonString)
                        // 更新内存缓存
                        cachedGameData = gameData

                        // 检查白泽厨师是否存在
                        val baizeChef = gameData.chefs.find { it.name == "白泽" }
                        if (baizeChef != null) {
                        } else {
                        }

                        Result.success("数据同步成功，时间戳：$timestamp")
                    } else {
                        Result.failure(Exception("数据格式验证失败"))
                    }
                } else {
                    Result.failure(Exception("网络响应为空"))
                }
            } else {
                Result.failure(Exception("网络请求失败：${response.code}"))
            }
        } catch (e: Exception) {
            Result.failure(e)
        }
    }
    
    /**
     * 保存游戏数据到内部存储
     */
    private fun saveGameDataToFile(jsonString: String) {
        try {
            val file = java.io.File(context.filesDir, "game_data.json")
            file.writeText(jsonString)
        } catch (e: Exception) {
            throw Exception("保存文件失败：${e.message}")
        }
    }
    

    
    /**
     * 解析JSON数据
     */
    private fun parseGameData(jsonString: String): GameData? {
        return try {
            // 解析原始JSON数据
            val jsonObject = gson.fromJson(jsonString, Map::class.java)
            
            // 提取各个数据类型
            val recipes = parseRecipes(jsonObject["recipes"] as? List<*>)
            val chefs = parseChefs(jsonObject["chefs"] as? List<*>)
            val equips = parseEquips(jsonObject["equips"] as? List<*>)
            val guests = parseGuests(jsonObject["guests"] as? List<*>)
            val materials = parseGameMaterials(jsonObject["materials"] as? List<*>)
            val condiments = parseCondiments(jsonObject["condiments"] as? List<*>)
            val skills = parseSkills(jsonObject["skills"] as? List<*>)
            val quests = parseQuests(jsonObject["quests"] as? List<*>)
            val ambers = parseAmbers(jsonObject["ambers"] as? List<*>)
            val decorations = parseDecorations(jsonObject["decorations"] as? List<*>)

            
            GameData(
                recipes = recipes,
                chefs = chefs,
                equips = equips,
                guests = guests,
                materials = materials,
                condiments = condiments,
                skills = skills,
                quests = quests,
                ambers = ambers,
                decorations = decorations
            )
        } catch (e: Exception) {
            null
        }
    }
    
    /**
     * 解析菜谱数据
     */
    private fun parseRecipes(data: List<*>?): List<Recipe> {
        return data?.mapNotNull { item ->
            try {
                val map = item as Map<*, *>
                Recipe(
                    recipeId = formatId(map["recipeId"]),
                    galleryId = map["galleryId"]?.toString() ?: "",
                    name = map["name"]?.toString() ?: "",
                    rarity = (map["rarity"] as? Double)?.toInt() ?: 0,
                    stirfry = (map["stirfry"] as? Double)?.toInt() ?: 0,
                    boil = (map["boil"] as? Double)?.toInt() ?: 0,
                    knife = (map["knife"] as? Double)?.toInt() ?: 0,
                    fry = (map["fry"] as? Double)?.toInt() ?: 0,
                    bake = (map["bake"] as? Double)?.toInt() ?: 0,
                    steam = (map["steam"] as? Double)?.toInt() ?: 0,
                    price = (map["price"] as? Double)?.toInt() ?: 0,
                    time = (map["time"] as? Double)?.toInt() ?: 0,
                    origin = map["origin"]?.toString() ?: "",
                    condiment = map["condiment"]?.toString() ?: "",
                    gift = map["gift"]?.toString() ?: "", // 添加gift字段解析
                    materials = parseRecipeMaterials(map["materials"] as? List<*>),
                    guests = parseRecipeGuests(map["guests"] as? List<*>)
                )
            } catch (e: Exception) {
                null
            }
        } ?: emptyList()
    }
    
    /**
     * 解析菜谱材料
     */
    private fun parseRecipeMaterials(data: List<*>?): List<RecipeMaterial> {
        return data?.mapNotNull { item ->
            try {
                val map = item as Map<*, *>
                RecipeMaterial(
                    material = map["material"]?.toString() ?: "",
                    quantity = (map["quantity"] as? Double)?.toInt() ?: 0
                )
            } catch (e: Exception) {
                null
            }
        } ?: emptyList()
    }
    
    /**
     * 解析菜谱贵客
     */
    private fun parseRecipeGuests(data: List<*>?): List<RecipeGuest> {
        return data?.mapNotNull { item ->
            try {
                val map = item as Map<*, *>
                RecipeGuest(
                    guest = map["guest"]?.toString() ?: "",
                    rarity = 1 // 真实数据中没有星级信息，默认设为1
                )
            } catch (e: Exception) {
                null
            }
        } ?: emptyList()
    }
    
    /**
     * 解析厨师数据
     */
    private fun parseChefs(data: List<*>?): List<Chef> {
        return data?.mapNotNull { item ->
            try {
                val map = item as Map<*, *>
                
                // 解析tags字段
                val tagsList = when (val tagsData = map["tags"]) {
                    is List<*> -> tagsData.mapNotNull {
                        when (it) {
                            is Double -> it.toInt()
                            is Int -> it
                            else -> null
                        }
                    }
                    else -> emptyList()
                }
                
                // 解析ultimateGoal字段
                val ultimateGoalList = when (val goalData = map["ultimateGoal"]) {
                    is List<*> -> goalData.mapNotNull {
                        when (it) {
                            is Double -> it.toInt()
                            is Int -> it
                            else -> null
                        }
                    }
                    else -> emptyList()
                }
                
                val chefName = map["name"]?.toString() ?: ""
                val chefIdRaw = map["chefId"]
                
                // 解析 ultimateSkillList
                val ultimateSkillList = when (val skillListRaw = map["ultimateSkillList"]) {
                    is List<*> -> {
                        skillListRaw.mapNotNull { skill ->
                            when (skill) {
                                is Double -> skill.toInt()
                                is Int -> skill
                                is String -> skill.toIntOrNull()
                                else -> null
                            }
                        }
                    }
                    else -> emptyList()
                }
                
                Chef(
                    chefId = formatId(map["chefId"]),
                    galleryId = map["galleryId"]?.toString() ?: "",
                    name = chefName,
                    rarity = parseIntField(map["rarity"]),
                    stirfry = parseIntField(map["stirfry"]),
                    boil = parseIntField(map["boil"]),
                    knife = parseIntField(map["knife"]),
                    fry = parseIntField(map["fry"]),
                    bake = parseIntField(map["bake"]),
                    steam = parseIntField(map["steam"]),
                    skill = parseIntField(map["skill"]),
                    ultimateSkillList = ultimateSkillList,
                    ultimateGoal = ultimateGoalList,
                    origin = map["origin"]?.toString() ?: "",
                    tags = tagsList,
                    // 采集点字段
                    meat = parseIntField(map["meat"]),
                    fish = parseIntField(map["fish"]),
                    veg = parseIntField(map["veg"]),
                    creation = parseIntField(map["creation"]),
                    diskDesc = map["diskDesc"]?.toString() ?: ""
                )
            } catch (e: Exception) {
                null
            }
        } ?: emptyList()
    }

    /**
     * 解析厨具数据
     */
    private fun parseEquips(data: List<*>?): List<Equip> {
        return data?.mapNotNull { item ->
            try {
                val map = item as Map<*, *>
                val skillList = when (val skillData = map["skill"]) {
                    is List<*> -> skillData.mapNotNull {
                        when (it) {
                            is Double -> it.toInt()
                            is Int -> it
                            else -> null
                        }
                    }
                    is Double -> listOf(skillData.toInt())
                    is Int -> listOf(skillData)
                    else -> emptyList()
                }

                Equip(
                    equipId = formatId(map["equipId"]),
                    galleryId = map["galleryId"]?.toString() ?: "",
                    name = map["name"]?.toString() ?: "",
                    rarity = (map["rarity"] as? Double)?.toInt() ?: 0,
                    skill = skillList,
                    origin = map["origin"]?.toString() ?: ""
                )
            } catch (e: Exception) {
                null
            }
        } ?: emptyList()
    }

    /**
     * 解析心法盘数据
     */
    private fun parseAmbers(data: List<*>?): List<Amber> {
        return data?.mapNotNull { item ->
            try {
                val map = item as Map<*, *>
                Amber(
                    amberId = formatId(map["amberId"]),
                    galleryId = map["galleryId"]?.toString() ?: "",
                    name = map["name"]?.toString() ?: "",
                    type = (map["type"] as? Double)?.toInt() ?: 0,
                    rarity = (map["rarity"] as? Double)?.toInt() ?: 0,
                    desc = map["desc"]?.toString() ?: "",
                    skill = when (val s = map["skill"]) {
                        is List<*> -> s.mapNotNull { (it as? Double)?.toInt() }
                        is Double -> listOf(s.toInt())
                        is Int -> listOf(s)
                        else -> emptyList()
                    },
                    amplification = (map["amplification"] as? Double)?.toInt() ?: 0,
                    origin = map["origin"]?.toString() ?: ""
                )
            } catch (e: Exception) {
                null
            }
        } ?: emptyList()
    }

    /**
     * 解析贵客数据
     */
    private fun parseGuests(data: List<*>?): List<Guest> {
        return data?.mapNotNull { item ->
            try {
                val map = item as Map<*, *>
                val name = map["name"]?.toString() ?: ""
                
                // 解析gifts字段
                val giftsData = map["gifts"] as? List<*> ?: emptyList<Any>()
                val gifts = giftsData.mapNotNull { giftItem ->
                    try {
                        val giftMap = giftItem as Map<*, *>
                        GuestGift(
                            recipe = giftMap["recipe"]?.toString() ?: "",
                            antique = giftMap["antique"]?.toString() ?: ""
                        )
                    } catch (e: Exception) {
                        null
                    }
                }
                
                Guest(name = name, gifts = gifts)
            } catch (e: Exception) {
                null
            }
        } ?: emptyList()
    }

    /**
     * 根据贵客名称推断星级
     */
    private fun getGuestRarity(name: String): Int {
        return when (name) {
            // 1星贵客
            "迷思吹法师", "大胃王", "屠夫老王", "白富美" -> 1
            // 2星贵客
            "丐帮帮主", "富二代", "大内侍卫", "官爷", "木良", "木优" -> 2
            // 3星贵客
            "刘备", "关羽", "张飞", "富人", "富太太" -> 3
            // 4星贵客
            "吕布", "貂蝉", "唐伯虎", "潇洒李白", "迷弟杜甫", "大明湖畔的美女", "黄月英", "苏轼", "诸葛亮", "武松", "容嬷嬷", "屈原" -> 4
            // 5星贵客
            "耶稣", "如来", "王子", "公主", "伯爵大人", "王母娘娘", "皇帝", "皇后", "太上皇" -> 5
            // 6星贵客
            "福神", "禄神", "寿神" -> 6
            // 默认1星
            else -> 1
        }
    }
    
    /**
     * 解析材料数据
     */
    private fun parseGameMaterials(data: List<*>?): List<Material> {
        return data?.mapNotNull { item ->
            try {
                val map = item as Map<*, *>
                Material(
                    materialId = map["materialId"]?.toString() ?: "",
                    name = map["name"]?.toString() ?: "",
                    rarity = (map["rarity"] as? Double)?.toInt() ?: 0,
                    origin = map["origin"]?.toString() ?: ""
                )
            } catch (e: Exception) {
                null
            }
        } ?: emptyList()
    }
    
    /**
     * 解析调料数据
     */
    private fun parseCondiments(data: List<*>?): List<Condiment> {
        return data?.mapNotNull { item ->
            try {
                val map = item as Map<*, *>
                Condiment(
                    condimentId = map["condimentId"]?.toString() ?: "",
                    name = map["name"]?.toString() ?: "",
                    skill = map["skill"]?.toString() ?: "",
                    origin = map["origin"]?.toString() ?: ""
                )
            } catch (e: Exception) {
                null
            }
        } ?: emptyList()
    }

    /**
     * 解析技能数据
     */
    private fun parseSkills(data: List<*>?): List<Skill> {
        return data?.mapNotNull { item ->
            try {
                val map = item as Map<*, *>
                
                // 解析effect字段
                val effectData = map["effect"] as? List<*>
                val effects = effectData?.mapNotNull { effectItem ->
                    try {
                        val effectMap = effectItem as Map<*, *>
                        SkillEffect(
                            condition = effectMap["condition"]?.toString() ?: "",
                            type = effectMap["type"]?.toString() ?: "",
                            conditionType = effectMap["conditionType"]?.toString() ?: "",
                            value = (effectMap["value"] as? Double)?.toInt() ?: 0,
                            cal = effectMap["cal"]?.toString() ?: "",
                            rarity = (effectMap["rarity"] as? Double)?.toInt() ?: 0
                        )
                    } catch (e: Exception) {
                        null
                    }
                } ?: emptyList()
                
                Skill(
                    skillId = (map["skillId"] as? Double)?.toInt() ?: 0,
                    desc = map["desc"]?.toString() ?: "",
                    effect = effects
                )
            } catch (e: Exception) {
                null
            }
        } ?: emptyList()
    }

    /**
     * 根据符文查询菜谱
     * 查询逻辑：遍历所有贵客的gifts，如果antique字段等于选择的符文，则返回对应的菜谱
     */
    suspend fun getRecipesByRune(runeName: String): List<Recipe> {
        return try {
            val gameData = loadGameData().getOrNull() ?: return emptyList()
            
            // 存储匹配的菜谱名称
            val matchingRecipeNames = mutableSetOf<String>()
            
            // 遍历所有贵客的礼物
            gameData.guests.forEach { guest ->
                guest.gifts.forEach { gift ->
                    if (gift.antique == runeName) {
                        matchingRecipeNames.add(gift.recipe)
                    }
                }
            }
            
            // 根据菜谱名称查找对应的菜谱对象
            gameData.recipes.filter { recipe ->
                matchingRecipeNames.contains(recipe.name)
            }
        } catch (e: Exception) {
            emptyList()
        }
    }

    /**
     * 获取所有符文列表（从贵客gifts中提取）
     */
    suspend fun getAllRunes(): List<String> {
        return try {
            val gameData = loadGameData().getOrNull() ?: return emptyList()
            
            val runes = mutableSetOf<String>()
            gameData.guests.forEach { guest ->
                guest.gifts.forEach { gift ->
                    if (gift.antique.isNotEmpty()) {
                        runes.add(gift.antique)
                    }
                }
            }
            
            runes.toList().sorted()
        } catch (e: Exception) {
            emptyList()
        }
    }

    /**
     * 创建模拟数据（用于测试）
     */
    private fun createMockData(): GameData {
        val mockGuests = listOf(
            Guest("白玉汤"),
            Guest("孟婆"),
            Guest("土地公"),
            Guest("灶王爷"),
            Guest("财神")
        )
        
        val mockRecipes = listOf(
            Recipe(
                recipeId = "1",
                galleryId = "1",
                name = "白切鸡",
                rarity = 1,
                knife = 5,
                boil = 3,
                price = 100,
                time = 300,
                origin = "粤菜",
                guests = listOf(
                    RecipeGuest("白玉汤", 1),
                    RecipeGuest("孟婆", 2)
                ),
                got = true,
                rank = 2
            ),
            Recipe(
                recipeId = "2",
                galleryId = "2",
                name = "麻婆豆腐",
                rarity = 2,
                stirfry = 8,
                knife = 2,
                price = 150,
                time = 400,
                origin = "川菜",
                guests = listOf(
                    RecipeGuest("孟婆", 2),
                    RecipeGuest("土地公", 3)
                ),
                got = true,
                rank = 3
            ),
            Recipe(
                recipeId = "3",
                galleryId = "3",
                name = "北京烤鸭",
                rarity = 4,
                bake = 15,
                knife = 8,
                price = 500,
                time = 1200,
                origin = "京菜",
                guests = listOf(
                    RecipeGuest("灶王爷", 4),
                    RecipeGuest("财神", 5)
                ),
                got = false,
                rank = 0
            )
        )

        val mockEquips = listOf(
            Equip(
                equipId = "1",
                galleryId = "1",
                name = "平底锅",
                rarity = 1,
                skill = listOf(50),
                origin = "基础厨具",
                got = true
            ),
            Equip(
                equipId = "2",
                galleryId = "2",
                name = "炒锅",
                rarity = 2,
                skill = listOf(100),
                origin = "基础厨具",
                got = true
            ),
            Equip(
                equipId = "3",
                galleryId = "3",
                name = "蒸笼",
                rarity = 3,
                skill = listOf(150),
                origin = "高级厨具",
                got = false
            )
        )

        return GameData(
            recipes = mockRecipes,
            equips = mockEquips,
            guests = mockGuests
        )
    }

    /**
     * 格式化ID，去掉.0后缀
     */
    private fun formatId(id: Any?): String {
        val idStr = id?.toString() ?: ""
        return if (idStr.endsWith(".0")) {
            idStr.substring(0, idStr.length - 2)
        } else {
            idStr
        }
    }
    
    /**
     * 解析整数字段（兼容Int、Double、String类型）
     */
    private fun parseIntField(value: Any?): Int {
        return when (value) {
            is Int -> value
            is Double -> value.toInt()
            is String -> value.toIntOrNull() ?: 0
            else -> 0
        }
    }
    
    /**
     * 解析任务数据
     */
    private fun parseQuests(data: List<*>?): List<Quest> {
        return data?.mapNotNull { item ->
            try {
                val map = item as Map<*, *>
                Quest(
                    questId = (map["questId"] as? Double)?.toInt() ?: 0,
                    goal = map["goal"]?.toString() ?: "",
                    conditions = parseQuestConditions(map["conditions"] as? List<*>)
                )
            } catch (e: Exception) {
                null
            }
        } ?: emptyList()
    }
    
    /**
     * 解析任务条件
     */
    private fun parseQuestConditions(data: List<*>?): List<QuestCondition> {
        return data?.mapNotNull { item ->
            try {
                val map = item as Map<*, *>
                QuestCondition(
                    skill = map["skill"]?.toString() ?: "",
                    rarity = (map["rarity"] as? Double)?.toInt() ?: 0,
                    rank = (map["rank"] as? Double)?.toInt() ?: 0,
                    num = (map["num"] as? Double)?.toInt() ?: 0
                )
            } catch (e: Exception) {
                null
            }
        } ?: emptyList()
    }
    
    /**
     * 解析装修数据
     */
    private fun parseDecorations(data: List<*>?): List<Decoration> {
        return data?.mapNotNull { item ->
            try {
                val map = item as Map<*, *>
                Decoration(
                    id = parseIntField(map["id"]),
                    icon = parseIntField(map["icon"]),
                    name = map["name"]?.toString() ?: "",
                    tipMin = parseIntField(map["tipMin"]).takeIf { it >= 0 },
                    tipMax = parseIntField(map["tipMax"]).takeIf { it >= 0 },
                    tipTime = parseIntField(map["tipTime"]).takeIf { it > 0 },
                    gold = (map["gold"] as? Double) ?: 0.0,
                    position = map["position"]?.toString() ?: "",
                    suit = map["suit"]?.toString() ?: "",
                    suitGold = (map["suitGold"] as? Double) ?: 0.0,
                    origin = map["origin"]?.toString() ?: ""
                )
            } catch (e: Exception) {
                null
            }
        } ?: emptyList()
    }
}
